package io.gitee.minelx.commontools.date;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;

public class Cursor<E> {

	private final List<E> items;

	private int index;

	public Cursor(List<E> items) {
		this.items = items;
		index = 0;
	}

	public List<E> popThem(Predicate<E> test) {
		List<E> result = new ArrayList<>();
		while (hasNext() && test.test(lookup())) {
			result.add(pop());
		}
		return result;
	}

	public E lookup() {
		return items.get(index);
	}

	public E pop() {
		if (!hasNext()) {
			throw new IllegalStateException("index out of items bound. index: " + index);
		}
		E result = items.get(index);
		index++;
		return result;
	}

	public boolean hasNext() {
		return index != items.size();
	}

	public void revert() {
		if (index == 0) {
			throw new IllegalStateException("cursor is never moved.");
		}
		index--;
	}

	public int getIndex() {
		return index;
	}
}
